<?php
include("../lib/FeedWriter.php");

date_default_timezone_set('America/Los_Angeles');

$dir = '/tmp';

$feed = new FeedWriter(ATOM);
$feed->setTitle('Downloads for project %PROJECT% on Google Code');
$feed->setLink(get_url());

// FIXME This should be the newest date from below.
$feed->setChannelElement('updated', date(DATE_ATOM , time()));

$items = scandir($dir);
foreach ($items as $name) {
	$fullpath = realpath($dir . DIRECTORY_SEPARATOR . $name);
	if (file_exists($fullpath) == true && is_dir($fullpath) == false) {
		// Is File
		$size = human_filesize(filesize($fullpath));
		$time = filemtime($fullpath);

		$item = $feed->createNewItem();
		$item->setTitle("{$name} ({$size})");
		$item->setLink(get_url() . '/' . $name);
		$item->setDate(date(DATE_ATOM , $time));

		$item->addElement('count', 0);
		$item->addElement('size', $size);

		//Now add the feed item
		$feed->addItem($item);
	}
}

$feed->genarateFeed();

// Extremely simple function to get human filesize.
// Credit: rommel at rommelsantor dot com
function human_filesize($bytes, $decimals = 2) {
	$sz = array(
		0 => ' Bytes',
		1 => ' KB',
		2 => ' MB',
		3 => ' GB',
		4 => ' TB'
	);

	$factor = floor((strlen($bytes) - 1) / 3);
	if ($factor == 0) {
		// You cant have partial bytes.
		$decimals = 0;
	}

	return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}

function get_url() {
	$protocol = 'http';
	$default_port = 80;

	// Check for SSL
	if (array_key_exists('HTTPS', $_SERVER) == true && $_SERVER['HTTPS'] == 'on') {
		$protocol = 'https';
		$default_port = 443;
	}

	$port = '';
	if ($_SERVER['SERVER_PORT'] != $default_port) {
		$port = ':' . $_SERVER['SERVER_PORT'];
	}

	return $protocol . '://' . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
}
